<template>
  <!--自定义编辑弹窗-->
  <BasicModal v-bind="$attrs" @register="register" :title="modalTitle" :width="650" @ok="handleOk" :destroyOnClose="true" :canFullscreen="true">
    <BasicForm @register="registerForm" class="performanceForm" />
  </BasicModal>
</template>

<script setup>
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { ref } from 'vue';
  import { editForm } from './departmentManage.data';
  import { handleData, getAsynDeptTree, createNewUnit } from './service';

  const emit = defineEmits(['success', 'register']);
  let isUpdate = false;
  let modalTitle = ref('编辑');
  let formSchemas = {
    labelCol: {
      span: 6,
    },
    wrapperCol: {
      span: 17,
    }, //表单布局
    schemas: editForm,
    showActionButtonGroup: false,
  };
  //注册表单
  const [
    registerForm,
    // eslint-disable-next-line @typescript-eslint/no-unused-vars,no-unused-vars
    { resetFields = () => {}, setFieldsValue = (p) => {}, updateSchema = (p) => {}, validate = () => {}, clearValidate = () => {} },
  ] = useForm(formSchemas);
  //注册弹窗对象 挂载关闭弹窗方法
  // eslint-disable-next-line @typescript-eslint/no-unused-vars,no-unused-vars
  const [register, { closeModal = () => {}, setModalProps = (p) => {} }] = useModalInner(async (data) => {
    isUpdate = data.isUpdate;
    updateSchema({
      field: 'orgName',
      label: '绩效关联部门',
      component: 'ApiTreeSelect',
      componentProps: ({ formModel }) => {
        return {
          api: getAsynDeptTree,
          parentCode: {
            key: 'id',
            parentKey: 'parentId',
          },
          fieldNames: {
            children: 'children',
            label: 'deptName',
            value: 'deptCode',
          },
          params: {
            id: data.record?.suitGroupCode,
          },
          // @ts-ignore
          onSelect: (v, node) => {
            formModel.orgCode = node.deptCode;
          },
          getPopupContainer: () => document.body,
        };
      },
      required: true,
    });
    resetFields(); //清空表单
    //写入数据
    setFieldsValue({
      ...data.record,
      // orgCodes: '10004368',
      managerCode: data.record.manager,
      manager: data.record.managerName,
    });
  });

  /**
   * 弹窗保存
   */
  async function handleOk() {
    try {
      let values = await validate();
      console.log('values', values);
      setModalProps({ confirmLoading: true });
      if (isUpdate) {
        values.manager = values.manager === values.managerName ? values.managerCode : values.manager;
        values.managerCode = null;
        values.managerName = null;
        await handleData(values);
      } else {
        await createNewUnit(values);
      }
      closeModal();
      emit('success'); //调用父组件事件刷新父组件表格
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>

<style scoped></style>
